package com.weasel.weixin.commons.message;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.client.methods.CloseableHttpResponse;

import com.google.common.collect.ImmutableMap;
import com.weasel.http.HttpClientSecretary;
import com.weasel.http.SimpleHttpUploadAndDownloadSecretary;
import com.weasel.http.handler.UploadHandler;
import com.weasel.http.helper.HttpResponseHelper;
import com.weasel.http.helper.HttpUrlHelper;
import com.weasel.weixin.commons.CommonRequest;
import com.weasel.weixin.commons.config.CommonConfig;
import com.weasel.weixin.commons.message.bean.group.Atricles;
import com.weasel.weixin.commons.message.bean.group.Group;

/**
 * 群发请求类
 * Created by Dylan on 2015/10/20.
 */
public abstract class GroupMessageSendRequest extends CommonRequest {


    public GroupMessageSendRequest(CommonConfig config) {
        super(config);
    }
    //上传图文消息内的图片获取URL
    public GroupMessageSendResponse uploadimg(Group group) throws ExecutionException, IOException{
    	
    	String uri=HttpUrlHelper.withURL(getUploadUploadimgURI()).addParam("access_token",getAccessToken()).build();
		
    	GroupMessageSendResponse groupMessageSendResponse = SimpleHttpUploadAndDownloadSecretary.upload(uri, new File[]{group.getFile()}, new UploadHandler<GroupMessageSendResponse>() {

			@Override
			public GroupMessageSendResponse handler(CloseableHttpResponse response) {
				
				try {
					return HttpResponseHelper.jsonResponseToEntity(response, GroupMessageSendResponse.class);
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		});
   
		return groupMessageSendResponse;
    }
    //上传图文消息素材
    public GroupMessageSendResponse uploadnews(List<Atricles> atricles) throws ExecutionException, IOException{
		
		String uri=HttpUrlHelper.withURL(getUploadnewsURI()).addParam("access_token",getAccessToken()).build();
		
		CloseableHttpResponse response= HttpClientSecretary.post()
														   .withURI(uri)
														   .withParam(ImmutableMap.of("articles", atricles))
														   .doIt();
		GroupMessageSendResponse groupMessageSendResponse=HttpResponseHelper.jsonResponseToEntity(response, GroupMessageSendResponse.class);
		
		HttpClientSecretary.release(response);
		return groupMessageSendResponse;
	}
    protected abstract String getUploadUploadimgURI();
    protected abstract String getUploadnewsURI();
}
